<template>
  <h1>添加用户</h1>
  <smart-form
    :fields="formFields"
    :form-data="userForm"
    babelWidth="120px"
    ref="userFormRef"
    @update:value="updateData"
  />
  <div class="form-actions">
    <el-button type="primary" @click="handleAddUser">提交</el-button>
    <el-button @click="handleFormReset">重置</el-button>
  </div>
</template>

<script lang="ts" setup>
import SmartForm from "@/components/SmartForm.vue";
import type { Field } from "@/components/SmartForm.vue";
import { reactive, ref } from "vue";
import { useRouter } from "vue-router";
// import { addUser } from "@/api/user";

import { useUserStore } from "@/stores/userStore";
const userStore = useUserStore();
const { addUser } = userStore;
const userFormRef = ref();
const router = useRouter();

type User = {
  username: string;
  gender: string;
};

const userForm = reactive({
  username: "",
  gender: 0,
});

const formFields: Field[] = [
  {
    type: "input",
    label: "用户名",
    name: "username",
    span: 8,
    attrs: {
      placeholder: "请输入用户名",
    },
  },
  {
    type: "radio",
    label: "性别",
    name: "gender",
    options: [
      { label: "男", value: "1" },
      { label: "女", value: "2" },
    ],
    attrs: {},
    span: 8,
  },
  {
    type: "checkbox",
    label: "技能",
    name: "skills",
    options: [
      { label: "Vue", value: "vue" },
      { label: "React", value: "react" },
    ],
    attrs: {},
    span: 8,
  },
  {
    type: "datepicker",
    label: "出生日期",
    name: "birthday",
    span: 8,
  },
  {
    type: "datepicker",
    label: "工作时间",
    name: "worktime",
    attrs: {
      type: "daterange",
      unlinkPanels: true,
      shortcuts: [
        {
          text: "Last week",
          value: () => {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            return [start, end];
          },
        },
        {
          text: "Last month",
          value: () => {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            return [start, end];
          },
        },
      ],
    },
  },
];

// 数据更新回调
const updateData = (val: User) => {
  console.log("表单数据更新:", val);
  // if (val.gender === 1) {
  // }
};

const handleAddUser = () => {
  const data = userFormRef.value.getFormData();
  addUser({ ...data, gender: data.gender === "1" ? "男" : "女" });
  router.push("/user.html");
  // addUser(formModel).then((res) => {
  //   console.log(res)
  // })
};

const handleFormReset = () => {
  userFormRef.value.reset();
};
</script>
